import { getRouters } from '@/api/menu'
import Router from "@/router";

const permission = {
    namespaced: true,
    state: {
        menu: []
    },
    mutations: {
        setMenu(state, val) {
            state.menu = val
        },
        //动态注册路由
        addMenu(state, route) {
            //判断缓存中是否有数据
            let menu = JSON.parse(localStorage.getItem('menus'))
            if (!menu) return
            // const menu = VueCookie.get('menus')
            // console.log('执行addMenu')
            state.menu = menu
            // console.log(menu)
            //组装动态路由的数据
            const menuArray = []
            menu.forEach(item => {
                if (item.children.length) {
                    item.children = item.children.map(item => {
                        item.component = () => import(`../pages/${item.pagePath}`)
                        item.meta = getComponentMeta(item)
                        return item
                    })
                    menuArray.push(...item.children)
                } else {
                    item.component = () => import(`../pages/${item.pagePath}`)
                    menuArray.push(item)
                }
            })
            // console.log('menuArray', menuArray)
            //路由的动态添加
            menuArray.forEach(item => {
                route.addRoute('manage', item)
            })
        }
    },
    actions: {
        GenerateRoutes({ commit }) {
            //获取路由菜单并存入到cookie当中
            getRouters().then((res) => {
                localStorage.setItem('menus', JSON.stringify(res.menus))
                commit('addMenu', Router)
            })
        }
    }
}

//设置路由的meta
function getComponentMeta(menu) {
    let meta = {}
    meta.title = menu.menuName
    return meta
}

export default permission